<template>
  <div id="app">
    <transition :name="routerTransition">
      <keep-alive>
        <router-view />
      </keep-alive>
    </transition>
  </div>
</template>

<script>
import { LocalStorage } from "@hips/vue-core";
import { getUserInfo } from './request/api'
import { getEnvParams, getUrl } from './tools/index'
import { router } from '@hips/plugin-dataset-vuex';
LocalStorage.setPre(process.env.VUE_APP_LOCALSTORAGE_PRE);

export default {
  name: "App",
    data () {
    return {
      urlParams: null,
      envTokenUse:true,
      routerTransition: "router-slide-left",
    }
  },
  mounted () {
    if (getEnvParams().tokenVal&&!location.href.includes('access_token')) {
     this.checkEnvToken()
    } else {
      this.init()
    }
  },
  methods: {
    init () {
      if (!location.href.includes('access_token')) {
        const url = getUrl()
        location.href = url
      } else {
        this.getQuery()
        if (this.urlParams) {
          this.setNewToken()
          this.$dsxRouter.push({
            name: getEnvParams().path || 'applications',
          })
        }
      }

    },
    /**
     * 存token
     */
    setNewToken () {
      const key = getEnvParams().key
      localStorage.setItem(
        key,
        `${this.urlParams.access_token}`,
      )
    },
    /**
     * token检查环境变量
     */
    checkEnvToken () {
      const envTokenVal = getEnvParams().tokenVal
      const key = getEnvParams().key
      const url = getUrl()
      localStorage.setItem(
        key,
        `${envTokenVal}`,
      )
      getUserInfo().then((res) => {
        if (res) {
            router.push({
              name: getEnvParams().path || 'applications',
            })
          }
      }).catch(() => {
          getEnvParams().tokenVal = null;
          location.href = url
        })
     },
    /**
     * token检查
     */
    checkToken () {
      const key = getEnvParams().key
      const url = getUrl()
      if (localStorage.getItem(key)) {
        getUserInfo().then((res) => {
          if (res) {
            this.$dsxRouter.push({
              name: getEnvParams().path || 'applications',
            })
          }
        }).catch(() => {
          location.href = url
        })
      } else {
        location.href = url
      }
    },
    /**
     * 获取url中参数
     */
    getQuery () {
      const paramsArray = location.href
        .split('?')[1]
        .split('&')
      const urlObject = {}
      paramsArray.forEach((item) => {
        const arr = item.split('=')
        urlObject[arr[0]] = arr[arr.length - 1]
      })
      this.urlParams = urlObject
    },
  },
};
</script>

<style lang="less">
@import "style/theme.less";
</style>
